<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use GuzzleHttp\Client as BaseClient;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class CommonController extends Controller
{
    /**
     * 发送短信验证码
     *
     * @return array
     * @throws GuzzleException
     */
    public function sendCode(): array
    {
        $phone = request('phone',null);
        if(!$phone){
            return retError([
                'msg'=>'手机号不能为空!'
            ]);
        }else{
            $vp = VerifyMobile($phone,true);
            if($vp['code'] == 0){
                return retError([
                    'msg'=>$vp['msg_zh']
                ]);
            }
        }
        $config = config('system_config.sms');
        $timeout = $config['code']['timeout'];
        $type = \request('type','smsCode');
        $type = strtolower($type);
        $md5 = 'SMS'.$phone.'-'.$type;
        $cacheKey = 'getSMSCode'.':' . md5($md5);
        $code = Cache::get($cacheKey);
        if(Cache::has($cacheKey)){
            $code = Cache::get($cacheKey);
        }
        if (!$code) {
            $randStr = str_shuffle('1234567890');
            $code = substr($randStr,0,6);
            Cache::put($cacheKey,$code,600);
        }
        $url = $config['url'];
        $vars = [
            'code'  => $code,
            'time' =>  $timeout,
        ];
        $param = [
            'appid' => $config['code']['appid'],
            'signature' => $config['code']['signature'],
            'project' => $config['code']['project'],
            'to' => $phone,
            'vars' => json_encode($vars),
        ];
        $client = new BaseClient([
            'verify'=>false,#测试环境不做验证
        ]);
        $response = $client->request('post', $url,[
            'form_params'=>$param,
            'timeout'=> $timeout
        ]);
        $data = $response->getBody()->getContents();
        $result = json_decode($data,true);
        if($result['status'] == 'success'){
            return ret([
                'data'=>$config['code']['resend_time']
            ]);
        }else{
            return retError([
                'msg'=>$result['msg'],
            ]);
        }
    }
}
